package constant.milk.toilet.timer;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import constant.milk.toilet.R;
import constant.milk.toilet.SuperActivity;
import constant.milk.toilet.broadcast.PushBroadcast;
import constant.milk.toilet.database.DbInsertQuery;
import constant.milk.toilet.dialog.MilkDialog;
import constant.milk.toilet.util.MilkUtil;
import constant.milk.toilet.widget.ToiletWidget;

public class TimerActivity extends SuperActivity
{
	private TextView hourTextView;
	private TextView minTextView;
	private TextView secTextView;

	private TextView minTitleTextView;
	private TextView secTitleTextView;

	private View resetView;
	private View startView;
	private View stopView;
	private View saveView;

	private TextView resetTextView;
	private TextView startTextView;
	private TextView stopTextView;
	private TextView saveTextView;

	private TimerTask task;
	private Timer timer;

	private MilkDialog okDialog;
	private MilkDialog failDialog;
	private MilkDialog maxDialog;

	private TextView tipTitleTextView;
	private TextView tipResetTextView;
	private TextView tipStartTextView;
	private TextView tipStopTextView;
	private TextView tipSaveTextView;
	private TextView tipColon1TextView;
	private TextView tipColon2TextView;
	private TextView tipColon3TextView;
	private TextView tipColon4TextView;

	private int[] widgetIds;

	private Handler mHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			SharedPreferences p = getSharedPreferences("pref", Activity.MODE_PRIVATE);

			int hour = p.getInt(getString(R.string.prefHour), 0);
			int min = p.getInt(getString(R.string.prefMin), 0);
			int sec = p.getInt(getString(R.string.prefSec), 0);

			hourTextView.setText(MilkUtil.getMinSecHour(hour) + " 시");
			secTextView.setText(MilkUtil.getMinSecHour(sec));
			minTextView.setText(MilkUtil.getMinSecHour(min));

			if (hour >= 23 && min >= 59 && sec >= 59)
			{
				if (timer != null)
				{
					timer.cancel();
					timer.purge();
					timer = null;
				}
				
				TimerManager tm = new TimerManager();
				tm.stopTimer(superContext);

				maxDialog = new MilkDialog(superContext,
						"최대 시간은 23시 59분 59초를 넘길 수 없어요.", new OnClickListener()
						{
							@Override
							public void onClick(View v)
							{
								maxDialog.dismiss();
							}
						}, null);

				maxDialog.setLeftTitle("확인");
				maxDialog.show();
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.timer_activity);

		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void onResume()
	{
		super.onResume();

		AppWidgetManager appWidgetManager = AppWidgetManager
				.getInstance(superContext);

		widgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(
				superContext, ToiletWidget.class));

		SharedPreferences p = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		long startTime = p.getLong(getString(R.string.prefStartTime), 0);

		boolean timerOnOff = p.getBoolean(getString(R.string.prefTimerOnOff), false);
		int hour = p.getInt(getString(R.string.prefHour), 0);
		int min = p.getInt(getString(R.string.prefMin), 0);
		int sec = p.getInt(getString(R.string.prefSec), 0);

		if (startTime != 0)
		{
			Calendar calN = Calendar.getInstance();
			calN.setTimeInMillis(0);
			calN.add(Calendar.HOUR_OF_DAY, hour);
			calN.add(Calendar.MINUTE, min);
			calN.add(Calendar.SECOND, sec);

			long termTime = calN.getTimeInMillis();

			Calendar calM = Calendar.getInstance();
			calM.setTimeInMillis(0);
			calM.add(Calendar.HOUR_OF_DAY, 23);
			calM.add(Calendar.MINUTE, 59);
			calM.add(Calendar.SECOND, 59);

			long hour24 = calM.getTimeInMillis();

			if (termTime >= hour24)
			{
				maxDialog = new MilkDialog(superContext,
						"최대 시간은 23시 59분 59초를 넘길 수 없어요.", new OnClickListener()
						{
							@Override
							public void onClick(View v)
							{
								maxDialog.dismiss();
							}
						}, null);

				maxDialog.setLeftTitle("확인");
				maxDialog.show();

				hour = 23;
				min = 59;
				sec = 59;

				hourTextView.setText(MilkUtil.getMinSecHour(hour) + " 시");
				minTextView.setText(MilkUtil.getMinSecHour(min));
				secTextView.setText(MilkUtil.getMinSecHour(sec));

				if (timer != null)
				{
					timer.cancel();
					timer.purge();
					timer = null;
				}
				
				TimerManager tm = new TimerManager();
				tm.stopTimer(superContext);
			} 
			else
			{
				hourTextView.setText(MilkUtil.getMinSecHour(hour) + " 시");
				secTextView.setText(MilkUtil.getMinSecHour(sec));
				minTextView.setText(MilkUtil.getMinSecHour(min));

				if (timerOnOff)
				{
					startTime();
				} 
				else
				{
					if (timer != null)
					{
						timer.cancel();
						timer.purge();
						timer = null;
					}
					
					TimerManager tm = new TimerManager();
					tm.stopTimer(superContext);
				}
			}
		} 
		else
		{
			hour = 0;
			min = 0;
			sec = 0;

			hourTextView.setText(MilkUtil.getMinSecHour(hour) + " 시");
			minTextView.setText(MilkUtil.getMinSecHour(min));
			secTextView.setText(MilkUtil.getMinSecHour(sec));

			if (timer != null)
			{
				timer.cancel();
				timer.purge();
				timer = null;
			}
			
			TimerManager tm = new TimerManager();
			tm.stopTimer(superContext);
		}
	}

	@Override
	protected void setFindViewId()
	{
		hourTextView = (TextView) findViewById(R.id.timerHourTextView);
		minTextView = (TextView) findViewById(R.id.timerMinTextView);
		secTextView = (TextView) findViewById(R.id.timerSecTextView);

		minTitleTextView = (TextView) findViewById(R.id.timerMinTitleTextView);
		secTitleTextView = (TextView) findViewById(R.id.timerSecTitleTextView);

		resetView = findViewById(R.id.timerResetView);
		startView = findViewById(R.id.timerStartView);
		stopView = findViewById(R.id.timerStopView);
		saveView = findViewById(R.id.timerSaveView);

		resetTextView = (TextView) findViewById(R.id.timerResetTextView);
		startTextView = (TextView) findViewById(R.id.timerStartTextView);
		stopTextView = (TextView) findViewById(R.id.timerStopTextView);
		saveTextView = (TextView) findViewById(R.id.timerSaveTextView);

		tipTitleTextView = (TextView) findViewById(R.id.timerTipTitleTextView);
		tipResetTextView = (TextView) findViewById(R.id.timerTipResetTextView);
		tipStartTextView = (TextView) findViewById(R.id.timerTipStartTextView);
		tipStopTextView = (TextView) findViewById(R.id.timerTipStopTextView);
		tipSaveTextView = (TextView) findViewById(R.id.timerTipSaveTextView);
		tipColon1TextView = (TextView) findViewById(R.id.timerTipColon1TextView);
		tipColon2TextView = (TextView) findViewById(R.id.timerTipColon2TextView);
		tipColon3TextView = (TextView) findViewById(R.id.timerTipColon3TextView);
		tipColon4TextView = (TextView) findViewById(R.id.timerTipColon4TextView);
	}

	@Override
	protected void setOnClick()
	{
		resetView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (timer != null)
				{
					timer.cancel();
					timer.purge();
					timer = null;
				}
				
				TimerManager tm = new TimerManager();
				tm.stopTimer(superContext);
				
				int hour = 0;
				int min = 0;
				int sec = 0;

				hourTextView.setText(MilkUtil.getMinSecHour(hour) + " 시");
				minTextView.setText(MilkUtil.getMinSecHour(min));
				secTextView.setText(MilkUtil.getMinSecHour(sec));

				setResetData();
			}
		});

		startView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (timer != null)
				{
					return;
				}

				SharedPreferences p = getSharedPreferences("pref", Activity.MODE_PRIVATE);

				int hour = p.getInt(getString(R.string.prefHour), 0);
				int min = p.getInt(getString(R.string.prefMin), 0);
				int sec = p.getInt(getString(R.string.prefSec), 0);

				if (hour >= 23 && min >= 59 && sec >= 59)
				{
					maxDialog = new MilkDialog(superContext,
							"최대 시간입니다. 다시 시작 할려면 RESET을 누르고 시작해 주세요.",
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									maxDialog.dismiss();
								}
							}, null);

					maxDialog.setLeftTitle("확인");
					maxDialog.show();

					return;
				}

				SharedPreferences.Editor e = p.edit();
				e.putLong(getString(R.string.prefStartTime), System.currentTimeMillis());
				e.commit();

				startTime();

				setWidgetStart();
			}
		});

		stopView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (timer != null)
				{
					timer.cancel();
					timer.purge();
					timer = null;
				}
				
				TimerManager tm = new TimerManager();
				tm.stopTimer(superContext);

				SharedPreferences p = getSharedPreferences("pref", Activity.MODE_PRIVATE);
				SharedPreferences.Editor e = p.edit();
				e.putBoolean(getString(R.string.prefTimerOnOff), false);
				e.commit();

				setWidgetStop();
			}
		});

		saveView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (timer != null)
				{
					timer.cancel();
					timer.purge();
					timer = null;
				}
				
				TimerManager tm = new TimerManager();
				tm.stopTimer(superContext);
				
				SharedPreferences p = getSharedPreferences("pref", Activity.MODE_PRIVATE);
				long startTime = p.getLong(getString(R.string.prefStartTime), 0);

				if (startTime == 0)
				{
					setResetData();
					
					okDialog = new MilkDialog(superContext,
							"타이머가 시작 되지 않았습니다.", new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									okDialog.dismiss();
								}
							}, null);
					okDialog.setLeftTitle("확인");
					okDialog.show();
					return;
				}

				if (setSaveData())
				{
					setResetData();
					
					okDialog = new MilkDialog(superContext, "저장에 성공 하였습니다.",
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									okDialog.dismiss();
									finish();
								}
							}, null);
					okDialog.setLeftTitle("확인");
					okDialog.show();
				} 
				else
				{
					setResetData();
					
					failDialog = new MilkDialog(superContext,
							"저장에 실패 하였습니다. 개발자에게 문의 해주세요.",
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									failDialog.dismiss();
								}
							}, null);
					failDialog.setLeftTitle("확인");
					failDialog.show();
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		minTextView.setTextSize(TEXT_SIZE + 20);
		secTextView.setTextSize(TEXT_SIZE + 20);

		minTitleTextView.setTextSize(TEXT_SIZE + 5);
		secTitleTextView.setTextSize(TEXT_SIZE + 5);

		resetTextView.setTextSize(TEXT_SIZE + 5);
		startTextView.setTextSize(TEXT_SIZE + 5);
		stopTextView.setTextSize(TEXT_SIZE + 5);
		saveTextView.setTextSize(TEXT_SIZE + 5);

		resetTextView.setTextColor(0xffffffff);
		startTextView.setTextColor(0xffffffff);
		stopTextView.setTextColor(0xffffffff);
		saveTextView.setTextColor(0xffffffff);

		tipTitleTextView.setTextSize(TEXT_SIZE + 5);

		tipResetTextView.setTextSize(TEXT_SIZE - 1);
		tipStartTextView.setTextSize(TEXT_SIZE - 1);
		tipStopTextView.setTextSize(TEXT_SIZE - 1);
		tipSaveTextView.setTextSize(TEXT_SIZE - 1);
		tipColon1TextView.setTextSize(TEXT_SIZE - 1);
		tipColon2TextView.setTextSize(TEXT_SIZE - 1);
		tipColon3TextView.setTextSize(TEXT_SIZE - 1);
		tipColon4TextView.setTextSize(TEXT_SIZE - 1);
	}

	private void setResetData()
	{
		SharedPreferences p = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		SharedPreferences.Editor e = p.edit();
		e.putLong(getString(R.string.prefStartTime), 0);
		e.putLong(getString(R.string.prefEndTime), 0);
		e.putInt(getString(R.string.prefHour), 0);
		e.putInt(getString(R.string.prefMin), 0);
		e.putInt(getString(R.string.prefSec), 0);
		e.putBoolean(getString(R.string.prefTimerOnOff), false);
		e.commit();

		setWidgetReset();
	}

	private void startTime()
	{
		SharedPreferences p = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		SharedPreferences.Editor e = p.edit();
		e.putBoolean(getString(R.string.prefTimerOnOff), true);
		e.commit();

		TimerManager tm = new TimerManager();
		tm.startTimer(superContext);
		
		task = new TimerTask()
		{
			@Override
			public void run()
			{
				Message msg = new Message();
				mHandler.sendMessage(msg);
			}
		};

		timer = new Timer();
		timer.schedule(task, 0, 500);
	}

	@Override
	protected void onDestroy()
	{
		if (timer != null)
		{
			timer.cancel();
			timer.purge();
			timer = null;
		}

		super.onDestroy();
	}

	private boolean setSaveData()
	{
		DbInsertQuery query = null;

		try
		{
			query = new DbInsertQuery(superContext, superDb);

			query.setBeginTansaction();

			SharedPreferences p = getSharedPreferences("pref", Activity.MODE_PRIVATE);

			HashMap<String, String> map = new HashMap<String, String>();

			Calendar cal = Calendar.getInstance();
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH);
			int day = cal.get(Calendar.DAY_OF_MONTH);

			long startTime = p.getLong(getString(R.string.prefStartTime), 0);

			map.put("year", year + "");
			map.put("month", month + "");
			map.put("day", day + "");
			map.put("starttime", startTime + "");

			int hour = p.getInt(getString(R.string.prefHour), 0);
			int min = p.getInt(getString(R.string.prefMin), 0);
			int sec = p.getInt(getString(R.string.prefSec), 0);

			Calendar calT = Calendar.getInstance();
			calT.setTimeInMillis(0);
			calT.add(Calendar.HOUR_OF_DAY, hour);
			calT.add(Calendar.MINUTE, min);
			calT.add(Calendar.SECOND, sec);

			Calendar calM = Calendar.getInstance();
			calM.setTimeInMillis(0);
			calM.add(Calendar.HOUR_OF_DAY, 23);
			calM.add(Calendar.MINUTE, 59);
			calM.add(Calendar.SECOND, 59);

			long termTime = calT.getTimeInMillis();

			long hour24 = calM.getTimeInMillis();

			if (termTime >= hour24)
			{
				termTime = hour24;
			}

			map.put("term", termTime + "");

			query.insertTimer(map);

			int alarmPush = p.getInt(getString(R.string.prefPushAlarm), 1);

			if (alarmPush > 1)
			{
				Intent intent = new Intent(superContext, PushBroadcast.class);
				PendingIntent sender = PendingIntent.getBroadcast(superContext,
						1, intent, PendingIntent.FLAG_CANCEL_CURRENT);

				AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
				manager.cancel(sender);
				
				int version = Build.VERSION.SDK_INT;
				
				if (version >= 19)
				{
					manager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (24 * 60 * 60000), sender);
				}
				else
				{
					manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (24 * 60 * 60000), sender);
				}

				SharedPreferences.Editor e = p.edit();

				e.putInt(getString(R.string.prefPushAlarm), 1);
				e.commit();
			}

			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally
		{
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}

		return true;
	}

	private void setWidgetReset()
	{
		if (widgetIds.length > 0)
		{
			Intent intent = new Intent(ToiletWidget.RESET);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(
					superContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

			AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
			manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
					pendingIntent);
		}
	}

	private void setWidgetStart()
	{
		if (widgetIds.length > 0)
		{
			Intent intent = new Intent(ToiletWidget.START);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(
					superContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

			AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
			manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
					pendingIntent);
		}
	}

	private void setWidgetStop()
	{
		if (widgetIds.length > 0)
		{
			Intent intent = new Intent(ToiletWidget.STOP);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(
					superContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

			AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
			manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
					pendingIntent);
		}
	}
}
